<template>
  <div id="userList">
    <div id="search">
      <el-input
        placeholder="搜索用户编号"
        size="small"
        icon="el-icon-search"
        v-model="searchId">
      </el-input>
    </div>
    <div id="add">
<!--      v-show="role == 'ROLE_SUPERADMIN'"-->
      <el-button type="primary" @click="addUser" size="small" >添加用户</el-button>
    </div>
    <div id="userTable">
      <el-table
        :data="filterInfo"
        style="margin-top: 20px">
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form inline class="demo-table-expand">
              <el-form-item label="用户编号">
                <span>{{ props.row.uId }}</span>
              </el-form-item>
              <el-form-item label="用户名称">
                <span>{{ props.row.uName }}</span>
              </el-form-item>
              <el-form-item label="用户性别">
                <span>{{ props.row.uSex }}</span>
              </el-form-item>
              <el-form-item label="已借书籍">
                <span v-for="(book,index) in props.row.bookNames" :key = index>{{book}}&nbsp&nbsp</span>
              </el-form-item>
              <el-form-item label="用户邮箱">
                <span>{{ props.row.uEmail }}</span>
              </el-form-item>
              <el-form-item label="过期未还数">
                <span>{{ props.row.overNumber }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column
          label="用户编号"
          prop="uId">
        </el-table-column>
        <el-table-column
          label="用户名称"
          prop="uName">
        </el-table-column>
        <el-table-column
          label="用户状态"
          prop="uBoolean">
          <template slot-scope="props">
            <span v-if="props.row.uBoolean === 0">
              正常&nbsp&nbsp<el-button @click="cancelUser(props.row)" type="text" size="small">注销</el-button>
            </span>
            <span v-if="props.row.uBoolean === 1">注销</span>
          </template>
        </el-table-column>
        <el-table-column
          label="重置密码"
          prop="uId">
          <template slot-scope="props">
            <el-button @click="resetPwd(props.row)" type="text" size="small">重置密码</el-button>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          prop="uBoolean">
          <template slot-scope="props">
            <el-button type="primary" icon="el-icon-edit" @click="editUser(props.row)" size="small"></el-button>
            <el-button type="primary" icon="el-icon-delete" @click="deleteUser(props.row)" size="small"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!--编辑用户弹窗-->
    <el-dialog title="用户信息" :visible.sync="displayShow" class="dialog">
      <el-form :model="addInfo" :rules="rules" ref="addInfo" label-width="100px">
        <el-form-item label="用户名称" prop="uName" class="formName">
          <el-input v-model="addInfo.uName" class="form"></el-input>
        </el-form-item>
        <el-form-item label="用户性别" prop="uSex" class="formName">
          <el-select v-model="addInfo.uSex" placeholder="请选择性别" class="form">
            <el-option label="男" value="男" ></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户邮箱" prop="uEmail" class="formName">
          <el-input v-model="addInfo.uEmail" class="form"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="sureButton('addInfo')" style="margin-left: 8%;margin-top: 30px">确定</el-button>
          <el-button @click="closedButton">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!--添加用户弹窗-->
    <el-dialog title="用户信息" :visible.sync="displayAddUser" class="dialog">
      <el-form :model="addInfo" :rules="rules" ref="addInfo" label-width="100px">
        <el-form-item label="用户名称" prop="uName" class="formName">
          <el-input v-model="addInfo.uName" class="form"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="uPassword" class="formName">
            <el-input v-model="addInfo.uPassword" class="form"></el-input>
        </el-form-item>
        <el-form-item label="用户邮箱" prop="uEmail" class="formName">
          <el-input v-model="addInfo.uEmail" class="form"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addSingleUser" style="margin-left: 8%;margin-top: 30px">确定</el-button>
          <el-button @click="closedButton">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!--修改密码的对话框-->
    <el-dialog title="修改密码" :visible.sync="dialogFormVisible">
      <el-form :model="ruleForm" status-icon :rules="passRules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="新密码" prop="pass">
          <el-input type="password" v-model="ruleForm.pass" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input type="password" v-model="ruleForm.checkPass" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm()">确认</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <Pages @getInfo="getAllUser" class="page" :total="total" :pageSize="pageSize"></Pages>
  </div>

</template>


<script>
import { getuserList,
  editUserStatus,
  editUserInfo,
  editUserPass,
  userDelete,
  addUser
} from "../../../api/userList"
import Pages from "../../../components/pages/Pages"
import { getRole } from "../../../utils/cacheProcessing";

export default {
    components:{
      Pages
    },
    data(){
      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.ruleForm.checkPass !== '') {
            this.$refs.ruleForm.validateField('checkPass');
          }
          callback();
        }
      };
      var validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.ruleForm.pass) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      return {
        total: 150,
        pageSize: 5,
        user:"",
        role:"",
        searchId: '', // 搜索Id
        displayAddUser:false,
        dialogVisible:false,
        dialogFormVisible:false,
        // checked: true,
        displayShow: false, // 添加/修改表单是否显示
        operationType: 1, // 由于新增和修改用的是同一个弹框，所以设置1，2来判断当前需要执行新增还是修改。1新增 2 修改
        userList: [],
        addInfo: {
          uId: '',
          uName: '',
          uPassword: '',
          uSex: '',
          uEmail: ''
        },
        rules: {
          uName: [
            { required: true, message: '请输入用户名称', trigger: 'blur' },
            { min: 3, message: '至少3位字符', trigger: 'blur' }
          ],
          uSex: [
            { required: true, message: '请选择性别', trigger: 'change' }
          ],
          uPassword: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 5, message: '至少5位字符', trigger: 'blur' }
          ],
          uEmail: [
            { required: true, message: '请输入邮箱', trigger: 'blur' }
          ]
        },
        ruleForm: {
          pass: '',
          checkPass: '',
        },
        passRules: {
          pass: [
            { validator: validatePass, trigger: 'blur' }
          ],
          checkPass: [
            { validator: validatePass2, trigger: 'blur' }
          ],
        },
      };
    },
    computed: {
      filterInfo () { // 根据输入的ID过滤信息
        const {searchId, userList} = this
        let fInfo = ''
        if (searchId !== '') {
          fInfo = userList.filter(p => p.uId === parseInt(searchId))
        } else {
          fInfo = this.userList
        }
        return fInfo
      }
    },
    mounted(){
      this.getAllUser()
    },
    created(){
      this.getAllUser(1)
      this.role = getRole()
    },
    methods: {
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});

      },
      submitForm() {
        this.confirm({
          content: "确认修改密码?",
          fn: ()=>{
            let requestData = {
              userId: this.user.uId,
              newPassword:this.ruleForm.checkPass
            }
            editUserPass(requestData).then(res=>{
              this.$messageOK("success", "修改用户"+this.user.uName+"密码成功！");
              this.dialogFormVisible=false
            })
          },
          catchfn: () => {
            this.$messageOK("warning", "修改密码失败！");
          }
        });
      },
      addSingleUser(){
        this.confirm({
          content: "确认添加用户?",
          fn: ()=>{
            let requestData = {
              uName: this.addInfo.uName,
              uEmail:this.addInfo.uEmail
            }
            addUser(requestData).then(res=>{
              console.log(res);
              this.$messageOK("success", "添加用户"+this.addInfo.uName+"成功");
              this.getAllUser();
              this.displayAddUser=false
            }).catch(err=>{
                console.log(err)
            })
          },
          catchfn: () => {

            this.$messageOK("warning", "添加用户"+this.addInfo.uName+"失败!");
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      handleCurrentChange(val) { // 显示第几页
        this.currentPage=val // 改变默认的页数
        // 切换页码时，要获取每页显示的条数
        this.getAllUser(1) // 获取当前页数列表
      },
      getAllUser (val){ // 从后端获取所有图书列表
        if(!val) val = 1
        let requestData = {
          pageNum: parseInt(val)
        }
        getuserList(requestData).then(res=>{
          //console.log(res)
          this.userList = res.data.data.datas
          this.total = res.data.data.totalNum
        }).catch(err=>{
          console.log('err')
        })
      },
      resetPwd (user) { // 重置密码
        this.dialogFormVisible = true
        this.user = user
        this.ruleForm.pass = this.ruleForm.checkPass = ''
      },
      deleteUser (user) { // 删除用户
        this.confirm({
          content: "确认删除该用户?",
          fn: () => {
            let requestData = {
              ids:user.uId
            }
            userDelete(requestData).then(res=>{
              this.$messageOK("success","删除"+user.uName+"成功")
              this.getAllUser()
            })
          },
          catchfn: () => {
            this.$messageOK("warning", "删除"+user.uName+"失败");
          }
        });
      },
      editUser (user) { // 编辑用户
        this.operationType = 2 // 设置operationType为2
        this.displayShow = true // 显示弹出层
        this.addInfo.uId = user.uId // 获取修改的用户ID

        this.addInfo.uName = user.uName
        this.addInfo.uEmail = user.uEmail
        this.addInfo.uSex = user.uSex
        this.addInfo.uPassword = user.uPassword
        this.dialogVisible = true
        //alert(user.uId+","+user.uName+","+user.uBook+","+user.uSex )
      },
      addUser () { // 添加用户
        this.displayAddUser = true // 显示表单
        this.operationType = 1 // 将operationType转换为1，就是将确定按钮执行新增操作。

        // 将弹出层中的数据设置为空
        this.addInfo.uName = ''
        this.addInfo.uSex = ''
        this.addInfo.uEmail = ''
        this.addInfo.uPassword = ''
      },
      cancelUser (user) { // 注销用户
       // console.log(user);
        this.confirm({
          content: "确认注销该用户?",
          fn: () => {
            let requestData = {
              userId:user.uId,
              uBoolean:1
            }
            editUserStatus(requestData).then(res=>{
              this.$messageOK("success","注销"+user.uName+"成功")
              this.getAllUser()
            })
          },
          catchfn: () => {
            this.$messageOK("warning", "注销"+user.uName+"失败");
          }
        });
      },
      closedButton () { // 关闭弹出框
        this.displayShow = false
      },
      sureButton (addInfo) { // 添加/修改的确定按钮
        this.displayShow = false;
        this.confirm({
          content: "确认更改该用户信息?",
          fn: ()=>{
            let requestData = {
              uId:this.addInfo.uId,
              uName:this.addInfo.uName,
              uSex:this.addInfo.uSex,
              uEmail: this.addInfo.uEmail
            }
            editUserInfo(requestData).then(res=>{
              this.$messageOK("success", "修改用户成功");
              this.getAllUser()
            })
          },
          catchfn: () => {
            this.$messageOK("warning", "修改用户失败！");
          }
        });
      },
    },
}
</script>

<style lang="scss" scoped>
#userList {
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
  #search {
    float: left;
    width: 49%;

  }
  #add {
    float: left;
    width: 10%;
    margin-left: 10px;
  }
  .form {
    margin-right: 20px;
    width: 80%;
  }
  .formName {
    margin-top: 30px;
  }
  // .demo-ruleForm {
  //   padding-top: 40px;
  //   border-radius: 30px;
  //   background-color: #ffffff;
  //   box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
  //   height: 400px;
  //   width: 360px;
  //   position: absolute;
  //   top: 50%;
  //   left: 50%;
  //   margin: -200px 0 0 -180px;
  // }
  #userTable {
     padding-top: 20px;
   }
  .page {
    margin-top: 10px;
    text-align:center
  }
}

</style>
